package com.javen.demo.annotation;

import cn.hutool.json.JSONUtil;
import com.javen.demo.entity.OpenSourceEntity;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

import java.lang.reflect.Field;

/**
 * 注解示例
 * @author Javen
 */
public class AnnotationDemo {

    @OpenSource
    OpenSourceEntity openSource;

    public OpenSourceEntity getOpenSource() {
        return openSource;
    }

    public void setOpenSource(OpenSourceEntity openSource) {
        this.openSource = openSource;
    }

    /**
     *  默认作用域为单例singleton作用域，设置为原型作用域
     */
    @Bean
    @Scope("prototype")
    public OpenSourceEntity openSource(){
         return OpenSourceEntity.builder()
                 .author("Javen")
                 .name("IJPay")
                 .url("https://gitee/javen205/IJPay")
                 .build();
    }

    public static void annotationProcess(AnnotationDemo annotationDemo) {
        for (Field field : annotationDemo.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(OpenSource.class)) {
                OpenSource openSource = field.getAnnotation(OpenSource.class);
                annotationDemo.setOpenSource(
                        new OpenSourceEntity(openSource.author(), openSource.name(), openSource.url())
                );
            }
        }
    }

    public static void main(String[] args) {
        AnnotationDemo annotationDemo = new AnnotationDemo();
        annotationProcess(annotationDemo);
        System.out.println(JSONUtil.toJsonStr(annotationDemo));

        // 获取注入容器中的 Bean
        // SpringBoot注解大全 https://www.cnblogs.com/ldy-blogs/p/8550406.html
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AnnotationDemo.class);
        OpenSourceEntity openSource = (OpenSourceEntity) context.getBean("openSource");
        System.out.println(JSONUtil.toJsonStr(openSource));

    }
}
